package vip.zhenzicheng.test.juc;

import sun.misc.Unsafe;
import vip.zhenzicheng.design_patterns.singleton.lazy.Singleton;

import java.lang.reflect.Field;

/**
 * 使用反射获取Unsafe实例
 *
 * @author zhenzicheng
 * @date 2023-02-03 19:01
 */
public class UseUnsafeWithReflection {
  public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
    // 直接使用报错 java.lang.SecurityException: Unsafe
    // Unsafe unsafe = Unsafe.getUnsafe();
    Field field = Unsafe.class.getDeclaredField("theUnsafe");
    field.setAccessible(true);
    // static不需要传递实例对象
    Unsafe unsafe = (Unsafe) field.get(null);
    Singleton instance = (Singleton) unsafe.allocateInstance(Singleton.class);
    System.out.println(instance);
  }
}
